const service = require("../../../../service/port.js");
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const uploadImage = require('../../../../utils/uploadImg/uploadImg.js')
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    unpayList: [],
    status: "4", //状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、交易成功5、交易关闭 6、已评价7、退货中 8、退货成功,9退货失败
    pageSize: 4,
    pageNum: 1,
    noData: false, // 是否有更多数据
    noDatas: false, //一条数据都没有

    showrefundsbtn: '', //申请退款
    refundShow: false,
    returnReson: '',
    refundarray: ['已收货', '未收货'],
    fileList: [],
    refundprogressShow: false,
    resons: '', //退款进度 退款原因
    images: [], //退款进度 品正图片
    returnMoney: '',
    currentOrder: '',
    returnCreateTime:'',
    appStu:0,//审批状态 0待审批 1 同意 2拒绝
    appResult:'',
    returnModifyTime:'',
    statusText:""
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getList(callback) {
    let customerId = wx.getStorageSync("userInfo").id;
    service.getTbOrderList({
        tbOrder: {
          customerId: customerId, //客户id
          status: this.data.status,
        },
        queryRequest: {
          pageSize: this.data.pageSize,
          pageNum: this.data.pageNum,
        },
      },
      (res) => {
         console.log(res)
        for (let i = 0; i < res.data.rows.length; i++) {
          const element = res.data.rows[i];
          if(element.timelyDelivery==1){
            
              this.setData({
                statusText:"已完成"
              })
            
            
          }else if(element.timelyDelivery==2){
            if(element.postStatus==1){
              this.setData({
                statusText:"未配送"
              })
            }else if(element.postStatus==2){
              this.setData({
                statusText:"配送中"
              })
            }else if(element.postStatus==3){
              this.setData({
                statusText:"已配送"
              })
            }else{
              this.setData({
                statusText:"配送异常"
              })
            }

          }else{
            this.setData({
              statusText:"到店自取"
            })
          }
          
        }
        callback(res);
      }
    );
  },
  onLoad: function () {
    var self = this;
    // 订单列表
    wx.showLoading({
      title: "加载中...",
    });
    this.getList(function (res) {
      if (res.data.total == 0) {
        self.setData({
          noDatas: true,
          noData:false
        });
      } else if (res.data.total > 0 && res.data.total < 4) {
        self.setData({
         
          noData: true,
        });
      }
       self.setData({
        unpayList: res.data.rows,
      });
      wx.hideLoading();
    });
  },
  //跳转到订单详情
  productdetail: function (e) {
    console.log(e);
    var index = e.currentTarget.dataset.index.id;
    wx.navigateTo({
      url: "/pages/order/orderDetail/index?id=" + index,
    });
  },
  unpayTo: function (e) {
    wx.redirectTo({
      url: "/pages/mine/order/unpayList/index",
    });
  },
  unreviceTo: function (e) {
    wx.redirectTo({
      url: "/pages/mine/order/unreviceList/index",
    });
  },
  completeTo: function (e) {
    wx.redirectTo({
      url: "/pages/mine/order/completeList/index",
    });
  },
  closerTo: function (e) {
    wx.redirectTo({
      url: "/pages/mine/order/closerList/index",
    });
  },
  refundTo: function (e) {
    wx.redirectTo({
      url: "/pages/mine/order/refundList/index",
    });
  },
  //删除订单 begin    
  deletelOrder: function (e) {

    console.log(e)
    Dialog.confirm({
        title: '提示',
        message: '确认删除该订单吗？',
      })
      .then(() => {
        // on confirm
        const self = this
        service.cancleTbOrder({
          "orderId": e.currentTarget.dataset.index.id, //订单标识
          "status": "10" //状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、交易成功5、交易关闭 6、已评价7、退货中 8、退货成功,9退货失败 10 删除订单
        }, function (res) {
          self.setData({
            pageSize: 4,
            pageNum: 1
          });
          self.onLoad()
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          })         
        })
      })
      .catch(() => {
        // on cancel
      });



  },
  // 删除订单 end

  //查看物流 begin
  checklogistic: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.index.orderNum
    wx.navigateTo({
      url: '/pages/order/logistics/index?id=' + index,
    })
  },
  //查看物流 end
   //申请退款按钮显示 隐藏
   togglebtn: function (e) {
    console.log(e)
    let index = e.currentTarget.dataset.index.id

    if(this.data.showrefundsbtn==index){
      this.setData({
        showrefundsbtn: false
      })
    }else{
      this.setData({
        showrefundsbtn: index
      })
    }


  },
  //申请退款 begin
  applyRefund: function (e) {
    console.log(e)
    this.setData({
      refundShow: true,
      cash: e.currentTarget.dataset.index.actualPay,
      currentOrder: e.currentTarget.dataset.index.id
    })
  },
  //
  refundClose: function (e) {
    this.setData({
      refundShow: false
    })
  },
  //
  //退款图片
  afterRead: function (e) {

    var list = this.data.fileList;
    list.push({
      url: e.detail.file.path
    })
    this.setData({
      fileList: list
    })
    console.log(this.data.fileList);
  },
  deletephoto: function (event) {
    const {
      index,
      name
    } = event.detail;
    const fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({
      fileList: fileList
    })

  },

  refundButton: function (e) {

  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  //退款原因
  getreturnReson: function (e) {
    this.setData({
      returnReson: e.detail.value
    })
  },
  confirmRefund: function () {
    // for (var i = 0; i < this.data.fileList.length; i++) {
    //   //显示消息提示框
    //   //上传图片
    //   //你的域名下的/images/当前年月日文件下的/图片.png
    //   //图片路径可自行修改【(这二个参数就是你oss地址目录的下一个路径目录，比如:https://xxx.com/images/xxx.png)】
    //   uploadImage(this.data.fileList[i].url, 'images/',
    //     function (result) {
    //       console.log("======上传成功图片地址为：", result);
    //       //这个result就是返给你上传到oss上的地址链接
    //       wx.hideLoading();
    //     }, function (result) {
    //       console.log("======上传失败======", result);
    //       wx.hideLoading()
    //     }
    //   )
    // }
    var self = this;
    wx.showLoading({
      title: '正在上传图片',
      mask: true
    })
    var imglist = []

    function uploadimg() {
      if (self.data.fileList.length > 0) {
        var imgpath = self.data.fileList.pop();
        uploadImage(imgpath.url, 'images/',
          function (result) {
            console.log("======上传成功图片地址为：", result);
            imglist.push(result)
            //这个result就是返给你上传到oss上的地址链接
            uploadimg()
          },
          function (result) {
            console.log("======上传失败======", result);
            Toast.fail('上传失败');            
            uploadimg()
          }
        )

      } else {
        service.applyRefund({
          "orderId": self.data.currentOrder, //订单标识
          "returnReson": self.data.returnReson, //退货原因
          "images": imglist.toString(), //凭证图片
          "appcustomerId": wx.getStorageSync('userInfo').id //审批人标识
        }, res => {       
          console.log(res)           
          self.setData({
            refundShow: false
          })
          Toast.success('申请成功'); 
          self.onLoad();
          wx.hideLoading();
        })

      }
    }
    uploadimg();

  },
  // 申请退款 end
  gocomment(e) {
    console.log(e);
    wx.navigateTo({
      url: '/pages/evaluate/index?spuId=' + e.currentTarget.dataset.index.spuId + "&orderDetAllId=" + e.currentTarget.dataset.index.orderDetAllId,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 请求数据
    wx.showNavigationBarLoading(); //在标题栏中显示加载
    this.setData({
      pageNum: 1,
      noData: false,
    });
    const self = this;
    this.getList(function (res) {
      if (res.data.rows.length > 0 && res.data.rows.length < 4) {
        self.setData({
          unpayList: res.data.rows,
          noData: true,
        });
      } else {
        self.setData({
          unpayList: res.data.rows,
        });
      }
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 判读数据是否加载完毕
    if (this.data.noData) return;
    // 停止下拉刷新
    wx.stopPullDownRefresh();
    wx.showNavigationBarLoading(); //在标题栏中显示加载
    const unpayList = this.data.unpayList;
    let pageNum = this.data.pageNum;
    this.setData({
      // 每次下拉 page+1
      pageNum: ++pageNum,
    });
    const self = this;
    self.getList(function (res) {
      if (res.data.rows.length == 0) {
        self.setData({
          noData: true,
        });
      } else {
        res.data.rows.forEach((item) => {
          unpayList.push(item);
        });
        self.setData({
          unpayList: unpayList,
        });
      }
    });
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});